<template>
  <div class="login-page">
    <div class="login-header">
      <div class="login-logo">
        <div class="login-title">铁路教育系统</div>
      </div>
    </div>
    <div class="login-body">
      <div class="login-left">
        <div class="login-desc">
          <h2>欢迎使用铁路教育系统</h2>
          <p>专业的铁路知识学习平台</p>
        </div>
      </div>
      <div class="login-form">
        <div class="form-tabs">
          <div
            :class="['tab-item', { active: activeTab === 'login' }]"
            @click="activeTab = 'login'"
          >登录</div>
          <div
            :class="['tab-item', { active: activeTab === 'register' }]"
            @click="activeTab = 'register'"
          >注册</div>
        </div>

        <!-- 登录表单 -->
        <el-form
          v-if="activeTab === 'login'"
          ref="loginForm"
          label-position="top"
          :model="loginForm"
          :rules="loginRules"
        >
          <el-form-item label="账号" prop="username">
            <el-input
              v-model="loginForm.username"
              size="medium"
              type="text"
              placeholder="请输入账号"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="loginForm.password"
              size="medium"
              type="password"
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="" style="margin-top: 20px">
            <el-button
              :loading="loading"
              style="width: 100%"
              type="primary"
              size="medium"
              @click="handleLogin"
            >登录</el-button>
          </el-form-item>
        </el-form>

        <!-- 注册表单 -->
        <el-form
          v-else
          ref="registerForm"
          label-position="top"
          :model="registerForm"
          :rules="registerRules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="registerForm.username"
              size="medium"
              type="text"
              placeholder="请输入用户名（4-20个字符）"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="registerForm.password"
              size="medium"
              type="password"
              show-password
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              size="medium"
              type="password"
              show-password
              placeholder="请再次输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input
              v-model="registerForm.nickname"
              size="medium"
              type="text"
              placeholder="请输入昵称（选填）"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="registerForm.email"
              size="medium"
              type="email"
              placeholder="请输入邮箱"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="registerForm.phone"
              size="medium"
              type="text"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-radio-group v-model="registerForm.role">
              <el-radio :label="0">学生</el-radio>
              <el-radio :label="1">教师</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" style="margin-top: 20px">
            <el-button
              :loading="loading"
              style="width: 100%"
              type="primary"
              size="medium"
              @click="handleRegister"
            >注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { http } from "@/api";
import {setToken} from "@/utils/ProjectTools";

export default {
  data() {
    // 密码验证规则
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.registerForm.confirmPassword !== '') {
          this.$refs.registerForm.validateField('confirmPassword');
        }
        callback();
      }
    };
    // 确认密码验证规则
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      const phoneReg = /^1[3-9]\d{9}$/;
      if (value && !phoneReg.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };

    return {
      loading: false,
      activeTab: 'login',
      loginForm: {
        username: "",
        password: "",
      },
      registerForm: {
        username: "",
        password: "",
        confirmPassword: "",
        nickname: "",
        email: "",
        phone: "",
        role: 0
      },
      loginRules: {
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
        ],
      },
      registerRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 4, max: 20, message: "用户名长度必须在4-20之间", trigger: "blur" }
        ],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
          { min: 6, message: "密码长度不能小于6位", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" }
        ],
        role: [
          { required: true, message: "请选择角色", trigger: "change" }
        ]
      }
    }
  },
  methods: {
    ...mapActions("user", ["login"]),

    // 处理登录
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          http.auth.login(this.loginForm)
            .then(res => {
              // 存储token
              setToken(res.data.token)
              // 获取用户信息
              return http.auth.getUserInfo(this.loginForm.username);
            })
            .then(res => {
              // 存储用户信息
              this.$store.commit('user/SET_USERINFO', res.data);
              this.$message.success('登录成功');
              this.$router.push(this.$route.query.redirect || '/');
            })
            .catch(error => {
              this.$message.error(error.message || '登录失败');
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    // 处理注册
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true;
          const { confirmPassword, ...registerData } = this.registerForm;
          http.auth.register(registerData)
            .then(() => {
              this.$message.success('注册成功，请登录');
              this.activeTab = 'login';
              this.$refs.registerForm.resetFields();
              // 自动填充登录表单
              this.loginForm.username = registerData.username;
              this.loginForm.password = registerData.password;
            })
            .catch(error => {
              this.$message.error(error.message || '注册失败');
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
// 添加文本省略的mixin
@mixin text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.login-page {
  background-color: #fafbfe;
  min-height: 100vh;

  .login-header {
    max-width: 1050px;
    margin: 0 auto 30px;
    padding: 1.5rem 0;
    display: flex;
    justify-content: space-between;
  }

  .login-logo {
    display: flex;
    align-items: center;
    .login-title {
      margin-left: 12px;
      font-size: 24px;
      font-weight: bold;
    }
  }

  .login-body {
    overflow: hidden;
    max-width: 1050px;
    position: relative;
    display: flex;
    align-items: center;
    flex-direction: row;
    margin: 0 auto;
    box-shadow: 0 19px 22px #e8ecf4;
    background-color: #ffffff;
    border-radius: 0 2% 2% 0;

    .login-left {
      height: 520px;
      background: #1e2a35;
      flex: 1;
      position: relative;
      color: #fff;
      vertical-align: middle;
      display: flex;
      flex-flow: column;
      align-items: center;
      justify-content: center;
      border-radius: 2% 0 0 2%;

      .login-desc {
        text-align: center;
        h2 {
          font-size: 28px;
          margin-bottom: 20px;
        }
        p {
          font-size: 16px;
          opacity: 0.8;
        }
      }
    }

    .login-form {
      height: 520px;
      max-width: 500px;
      padding: 2rem;
      background-color: #fff;
      position: relative;
      width: 100%;
      align-items: center;
      border-radius: 0 2% 2% 0;
      box-sizing: border-box;
      overflow-y: auto;

      .form-tabs {
        display: flex;
        margin-bottom: 20px;
        border-bottom: 1px solid #ebeef5;

        .tab-item {
          flex: 1;
          text-align: center;
          padding: 10px 0;
          cursor: pointer;
          color: #909399;
          font-size: 16px;

          &.active {
            color: #409EFF;
            border-bottom: 2px solid #409EFF;
          }
        }
      }

      .el-form-item {
        margin-bottom: 1rem;
      }

      .el-form-item__label {
        color: #6c757d;
        font-weight: 600;
        font-size: 14px;
        padding-bottom: 4px;
      }
    }
  }
}
</style>
